package com.company.manage.common.utils;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Created by HuangYong on 2016/1/22.
 * desc:异常的工具类.
 */
public class Exceptions {
    private static final String TAG = "Exceptions";

    /**
     * 将CheckedException转换为UncheckedException.
     */
    public static RuntimeException unchecked(Exception e) {
        if (e instanceof RuntimeException) {
            return (RuntimeException) e;
        } else {
            return new RuntimeException(e);
        }
    }

    /**
     * 将ErrorStack转化为String.
     *
     * @param e
     * @return
     */
    public static String getStackTraceAsString(Exception e) {
        StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        return stringWriter.toString();
    }

    /**
     * 判断异常是否由某些底层的异常引起的
     *
     * @param ex
     * @return
     */
    public static boolean isCauseBy(Exception ex, Class<? extends Exception>... classes) {
        Throwable cause = ex;
        while (cause != null) {
            for (Class<? extends Exception> causeClass : classes) {
                if (causeClass.isInstance(cause)) {
                 return true;
                }
            }
            cause = cause.getCause();
        }
        return false;
    }

}